package collisions 
{
	import entities.Entity;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	/**
	 * ...
	 * @author Gareth Williams
	 * todo: narrowphase collision - may not be necessary for this game...
	 * todo: extract broadphase to interface.
	 */
	public class World
	{
		public static const bodies:Dictionary = new Dictionary(true);
		public function addBody(body:Body):void
		{
			bodies[body] = true;
		}
		public function removeBody(body:Body):void
		{
			bodies[body] = null; //hopefully releases reference for gc...
		}
		public function update():void
		{
			QuadTree.LEAFS = new Dictionary(); //clear previous dictionary
			var broadPhase:QuadTree = new QuadTree(0, 0, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT);
			
			//construct tree
			for (var collidee:Object in bodies)
			{
				if (bodies[collidee] != false)
					broadPhase.addChild(collidee as Body); //implicitly cast null to false
			}
		
			//check for potential collision groups
			var query:Rectangle =
				new Rectangle(
					0, 0, Constants.MINIMUM_QUADTREE_AREA, Constants.MINIMUM_QUADTREE_AREA);
			var offset:Number = Constants.MINIMUM_QUADTREE_AREA * 0.5;
			
			for (var collider:Object in bodies)
			{
				//centre the rectangle...
				query.x = Body(collider).x - offset;
				query.y = Body(collider).y - offset;
				
				for (var node:Object in QuadTree.LEAFS)
				{
					if (false == query.intersects(node as Rectangle)) continue;
					
					//todo:final body element is not being checked for some reason...
					var child:LinkedList = QuadTree(node).children.next;
					while (child !== null)
					{
						if (child.object !== collider)
							collider.processProximityTo(child.object);
							
						child = child.next;
					}
				}
			}
		}
	}
}